import React, { useEffect, useRef } from 'react';

const LoginPage: React.FC = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const stars: { x: number; y: number; radius: number; vx: number; vy: number }[] = [];

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    const resizeCanvas = () => {
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
      createStars();
    };

    const createStars = () => {
      stars.length = 0;
      const numStars =400;
      for (let i = 0; i < numStars; i++) {
        stars.push({
          x: Math.random() * canvas.width,
          y: Math.random() * canvas.height,
          radius: Math.random() * 2,
          vx: Math.random() - 0.5, // 设置星星的水平速度
          vy: Math.random() - 0.5, // 设置星星的垂直速度
        });
      }
    };

    const drawStars = () => {
      if (!ctx) return;
      ctx.fillStyle = '#020919';
      ctx.fillRect(0, 0, canvas.width, canvas.height); // 使用黑色填充整个画布
      ctx.fillStyle = '#01e7ff';
      for (let i = 0; i < stars.length; i++) {
        const star = stars[i];
        ctx.beginPath();
        ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2);
        ctx.fill();
      }
    };

    const updateStars = () => {
      for (let i = 0; i < stars.length; i++) {
        const star = stars[i];
        star.x += star.vx;
        star.y += star.vy;
        if (star.x < 0 || star.x > canvas.width) {
          star.vx = -star.vx;
        }
        if (star.y < 0 || star.y > canvas.height) {
          star.vy = -star.vy;
        }
      }
    };

    const animate = () => {
      drawStars();
      updateStars();
      requestAnimationFrame(animate);
    };

    resizeCanvas();
    animate();

    window.addEventListener('resize', resizeCanvas);

    return () => {
      window.removeEventListener('resize', resizeCanvas);
    };
  }, []);

  return <canvas ref={canvasRef} style={{ position: 'absolute', top: 0, left: 0 }} />;
};

export default LoginPage;
